package com.pmcc.utils;



import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Comparator;

/**
 * Created by Tomas on 2018/4/16.
 * 指定数据排序
 */
public class CompareUtil implements Comparator<Object>{

    public int compare(Object ob1, Object ob2) {
        String comp1=null;
        String comp2=null;
        try{
            Class c1 = ob1.getClass();
            Class c2 = ob2.getClass();
            //获取该类的成员变量
            Field[] declaredFields1 = c1.getDeclaredFields();
            Field[] declaredFields2 = c2.getDeclaredFields();
//            对比的是该对象第一个成员变量，并对其排序
            comp1=(String)this.getFieldValueByName(declaredFields1[0].getName(),ob1);
            comp2=(String)this.getFieldValueByName(declaredFields2[0].getName(),ob2);
        }catch (Exception e) {

        }
        return comp1.compareTo(comp2);
    }

    /**
     * 根据属性名获取属性值
     * */
    private Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {
            return null;
        }
    }
}
